package logic

import (
	"context"
	"strings"

	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type RoleListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRoleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RoleListLogic {
	return &RoleListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RoleListLogic) RoleList(in *backend.RoleListRequest) (*backend.RoleListResponse, error) {
	logx.Infof("RoleListRequest : %+v ", in)

	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			if orderBy.Field == "id" {
				var order string = " ASC"
				if orderBy.Order == "1" {
					order = " DESC"
				}
				orderBys = append(orderBys, model.BackendRoleColumns.RoleID + order)
			}
		}
	}
	var stati string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			if filterBy.Field == "status" {
				stati = filterBy.In
			}
		}
	}
	roleList, count, err := l.svcCtx.BackendRole.GetList(l.ctx, model.M{
		"page":                          in.Current,
		"pageSize":                      in.PageSize,
		model.BackendRoleColumns.RoleID: in.RoleId,
		model.BackendRoleColumns.Name:   in.Name,
		model.BackendRoleColumns.Status: in.Status,
		"orderBy":                       strings.Join(orderBys, ","),
		"stati":                         stati,
	}, 1)
	if err != nil {
		return nil, err
	}

	var roles []*backend.RoleListItem
	if len(roleList) > 0 {
		for _, role := range roleList {
			roles = append(roles, &backend.RoleListItem{
				Id:        int64(role.RoleID),
				Name:      role.Name,
				Note:      role.Note,
				Status:    int32(role.Status),
				DelStatus: int32(role.DelStatus),
				CreatedAt: role.CreatedAt.Format("2006-01-02 15:04:05"),
				UpdatedAt: role.UpdatedAt.Format("2006-01-02 15:04:05"),
			})
		}
	}

	return &backend.RoleListResponse{
		Total: count,
		List:  roles,
	}, nil
}
